<?php
/**
 * ----------------------------------------------------------
 * date: 2019/6/10 8:42
 * ----------------------------------------------------------
 * author: Raoxiaoya
 * ----------------------------------------------------------
 * describe: 记录响应日志
 * ----------------------------------------------------------
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use App\Service\Log\LogFile;

//use Illuminate\Support\Facades\Log;

class ResponseLog
{

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{
            $logger   = new LogFile();
            $cline    = chr(10);
            $response = $next($request);
            $return   = json_encode(json_decode($response->getContent(), 1), JSON_UNESCAPED_UNICODE).$cline;

            // 保存返回数据
            $time = (microtime(true) - LARAVEL_START) * 1000;
            $log  = $request->getPathInfo().' | [RunTime:'.$time.'ms]';

            $logger->write($log, 'Response');
            if(strlen($return) <= 1000){
                $logger->write($return, 'return');
            }

            // 保存sql语句到日志中
            $queries = DB::getQueryLog();
            foreach($queries as $query){
                $sql = str_replace('?', '\'%s\'', $query['query']);
                $sql = vsprintf($sql, $query['bindings']);
                $log = $sql.'; [RunTime:'.$query['time'].'ms]';
                $logger->write($log, 'SQL');
            }

            return $response;
        } catch(\HttpException $e){
            return ['code' => $e->getStatusCode(), 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        } catch(\Exception $e){
            return ['code' => 1, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        }

    }
}

